package com.hmy.infrastructure.common.utils;

import com.hmy.infrastructure.api.bo.response.dingtalk.AppTokenResponse;
import com.hmy.infrastructure.common.properties.DingTalkProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Component
public class DingTalkUtil {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DingTalkProperties dingTalkProperties;

    private final Map<String, String> accessTokenMap = new HashMap<>();

    public AppTokenResponse getAccessToken() throws URISyntaxException {
        StringBuilder url = new StringBuilder(dingTalkProperties.getAccessTokenUrl());
        url.append("?appkey=").append(dingTalkProperties.getAppKey());
        url.append("&appsecret=").append(dingTalkProperties.getAppSecret());
        URI uri = new URI(url.toString());
        return restTemplate.getForObject(uri, AppTokenResponse.class);
    }

    /**
     * 构造请求地址
     *
     * @param baseUrl 原始url
     * @return 路径
     */
    public String createUrl(String baseUrl) throws URISyntaxException {
        String accessToken = accessTokenMap.get("accessToken");
        if (StringUtils.isBlank(accessToken)) {
            accessToken = getAccessToken().getAccessToken();
            accessTokenMap.put("accessToken", accessToken);
        }
        return baseUrl + "?access_token=" + accessToken;
    }

    /**
     * 构造请求地址
     *
     * @param baseUrl 原始url
     * @return 路径
     */
    public String createUrlWithOutCache(String baseUrl) throws URISyntaxException {
        String accessToken = getAccessToken().getAccessToken();
        return baseUrl + "?access_token=" + accessToken;
    }

    public void clearToken() {
        accessTokenMap.clear();
    }

}
